package com.httptest.api;

import com.httptest.bean.DujitangOutputDTO;
import com.httptest.service.TestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;

/**
 * @author ricky
 * @date 2022/4/17 14:14
 */
@Api(tags = "测试控制器")
@RestController
@RequestMapping("/test")
public class TestController {

    @SneakyThrows
    @ApiOperation("测试")
    @GetMapping("/test")
    public void test() {
        OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        httpBuilder.connectTimeout(6, TimeUnit.SECONDS);
        // 使用拦截器在request中添加统一header内容
        httpBuilder.addInterceptor(chain -> {
            Request.Builder requestBuilder = chain.request().newBuilder();
            requestBuilder.addHeader("rwt", "default");
            System.out.println("headers");
            return chain.proceed(requestBuilder.build());
        });
        // 添加日志拦截器
        httpBuilder.addInterceptor(new HttpLoggingInterceptor(System.out::println).setLevel(HttpLoggingInterceptor.Level.BASIC));
        Retrofit retrofit = new Retrofit.Builder().client(httpBuilder.build())
                //设置网络请求BaseUrl地址
                .baseUrl("https://api.nextrt.com")
                //设置数据解析器
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(new ExecutorCallAdapterFactory())
                .build();

        TestService testService = retrofit.create(TestService.class);


        try {
            DujitangOutputDTO dujitang = testService.dujitang();
            System.out.println(dujitang);
        } catch (Exception e) {
            System.out.println("请求异常了");
        }
        // Response<DujitangOutputDTO> execute = dujitang.execute();
        // System.out.println(execute.body());

    }

    public static class ExecutorCallAdapterFactory extends CallAdapter.Factory {

        @Nullable
        @Override
        public CallAdapter<?, ?> get(@NotNull Type returnType, @NotNull Annotation[] annotations, @NotNull Retrofit retrofit) {
            if (getRawType(returnType) == Call.class) {
                throw new RuntimeException("interface直接返回responseBody");
            }
            return new CallAdapter<Object, Object>() {
                @NotNull
                @Override
                public Type responseType() {
                    return returnType;
                }

                @SneakyThrows
                @Override
                public Object adapt(@NotNull Call<Object> call) {
                    Response<Object> execute = call.execute();
                    if (execute.isSuccessful()) {
                        return execute.body();
                    }
                    throw new RuntimeException(execute.code() + ":" + execute.message());
                }
            };
        }
    }
}
